package org.zoomdev.zoom.dao.impl;

import org.zoomdev.zoom.dao.Sql;
import org.zoomdev.zoom.dao.adapters.StatementAdapter;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class SqlConfig {

    StringBuilder select = new StringBuilder();
    String filter;


    //忽略null值，insert update有效
    boolean ignoreNull;

    //忽略实体类之中的主键    update有效
    boolean ignorePk;

    StringBuilder sql = new StringBuilder();
    List<Object> values = new ArrayList<>();
    List<Object> updateValues = new ArrayList<>();


    List<StatementAdapter> adapters = new ArrayList<>();


    StringBuilder tmp = new StringBuilder();
    //
    Map<String, Sql.PlaceHolder> placeholder = new LinkedHashMap<>();

    void clear() {
        placeholder.clear();
        sql.setLength(0);
        values.clear();
        select.setLength(0);
        tmp.setLength(0);
        adapters.clear();
        updateValues.clear();
        filter = null;
        ignoreNull = true;
        ignorePk = false;
    }

    public void prepare(PreparedStatement ps) throws SQLException {
        int index = 0;
        //update在前
        for (int i = 0, c = adapters.size(); i < c; ++i) {
            index = i + 1;
            Object value = updateValues.get(i);
            StatementAdapter adapter = adapters.get(i);
            adapter.adapt(ps, index, value);
        }

        //where在后
        for (int i = 0, c = values.size(); i < c; ++i) {
            int currentIndex = index + i + 1;
            Object value = values.get(i);
            ps.setObject(currentIndex, value);
        }
    }

}
